package com.dk.controller;

import com.dk.RES;
import com.dk.pojo.User;
import com.dk.pojo.WeChatUserProfile;
import com.dk.pojo.UserInfo;
import com.dk.service.UserService;

import com.jack.weChatSecurity.core.SecurityHelper;
import com.jack.weChatSecurity.core.WeChatUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/api")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/user")
    @ResponseBody
    public RES getUsersInfoByQuery(@RequestParam("userId")String[] userIds){
        RES res=new RES();
        try {
            List<User> users=new ArrayList<>();
            for(String userId:userIds) {
                User user = userService.getUser(userId);
                users.add(user);
            }
            res.setCode(0).setMsg("okQuery")
                    .addData("users",users);
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(1).setMsg("error");
        }finally {
            return res;
        }
    }

    @PostMapping("/user")
    @ResponseBody
    public RES getUsersInfoByBody(@RequestBody String[] userIds){
        RES res=new RES();
        try {
            List<User> users=new ArrayList<>();
            for(String userId:userIds) {
                User user = userService.getUser(userId);
                users.add(user);
            }
            res.setCode(0).setMsg("okBody")
                    .addData("users",users);
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(1).setMsg("error");
        }finally {
            return res;
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public RES loginIn(){
        RES res=new RES();
        WeChatUser weChatUser = SecurityHelper.getWeChatUser();
        try{
            User user=userService.getUser(weChatUser.getId());
            res.setCode(0)
                    .setMsg("登陆成功")
                    .addData("user",user);
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(1).setMsg("登陆失败");
        }finally {
            return res;
        }
    }

    @PostMapping("/register")
    @ResponseBody
    public RES register(@RequestParam("code")String code, @RequestBody WeChatUserProfile weChatUserProfile){
        RES res=new RES();
        try{
            String token=SecurityHelper.register(code);
            WeChatUser weChatUser = SecurityHelper.getWeChatUser();
            User user;
            //判断是否注册过
            if(userService.haveUser(weChatUser.getId())){
                //之前注册完后很久没有使用token过期重新认证
                user=doReAuthenticate(weChatUserProfile);
                weChatUser.setAttribute("stuId",user.getStuId());
                userService.updateUser(user);
            }else{
                //第一次使用服务
                user=doRegister(weChatUserProfile);
                weChatUser.setAttribute("stuId",user.getStuId());
                userService.saveUser(user);
            }

            res.setCode(0)
                    .setMsg("注册成功")
                    .addData("user",user)
                    .addData("token",token);
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(1).setMsg("注册失败");
        }finally {
            return res;
        }
    }

    @PostMapping("/bind")
    @ResponseBody
    public RES updateStuId(@RequestParam("stuId") String stuId){
        RES res=new RES();
        WeChatUser weChatUser = SecurityHelper.getWeChatUser();
        weChatUser.setAttribute("stuId",stuId);
        try{
            User user=userService.updateStuId(weChatUser.getId(), stuId);
            res.setCode(0)
                    .setMsg("绑定成功")
                    .addData("user",user);
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(1).setMsg("绑定失败");
        }finally {
            return res;
        }
    }

    @DeleteMapping("/logout")
    @ResponseBody
    public RES loginOut(){
        RES res=new RES();
        SecurityHelper.logout();
        res.setCode(0).setMsg("注销成功");
        return res;
    }

    /**
     * 注册
     * @param weChatUserProfile
     * @return
     */
    private User doRegister(WeChatUserProfile weChatUserProfile){
        User user=new User();

        UserInfo weChatUserInfo=weChatUserProfile.getUserInfo();
        user.setId(SecurityHelper.getWeChatUser().getId());
        user.setAvatarUrl(weChatUserInfo.getAvatarUrl());
        user.setNickName(weChatUserInfo.getNickName());
        user.setGender(weChatUserInfo.getGender());

        return user;
    }

    /**
     * 重新认证
     * @param weChatUserProfile
     * @return
     */
    private User doReAuthenticate(WeChatUserProfile weChatUserProfile) throws Exception {
        User user=userService.getUser(SecurityHelper.getWeChatUser().getId());
        UserInfo userInfo=weChatUserProfile.getUserInfo();
        user.setNickName(userInfo.getNickName());
        user.setGender(userInfo.getGender());
        user.setAvatarUrl(userInfo.getAvatarUrl());
        return user;
    }
}
